package com.programming.forum.services.impl;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-11-06
 * Time: 9:16
 */

import com.programming.forum.common.AppResult;
import com.programming.forum.common.ResultCode;
import com.programming.forum.dao.MessageMapper;
import com.programming.forum.dao.UserMapper;
import com.programming.forum.exception.ApplicationException;
import com.programming.forum.model.User;
import com.programming.forum.services.IUserService;
import com.programming.forum.utils.MD5Util;
import com.programming.forum.utils.StringUtil;
import com.programming.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * IuserService 接口实现类
 * 用户相关业务实现
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private MessageMapper messageMapper;

    @Override
    public void createNormalUser(User user) {
        //非空校验
        if(user == null || StringUtil.isEmpty(user.getUsername())
        || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())
        || StringUtil.isEmpty(user.getSalt())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常 - ApplicationException FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //查询用户名是否已被使用
        User existsUser = userMapper.selectByUserName(user.getUsername());
        //判断用户名是否存在
        if(existsUser != null) {
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常 - ApplicationException FAILED_USER_EXISTS      (1101,"用户已存在"),
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        //设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        //当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //写入数据库
        int row = userMapper.insertSelective(user);
        //判断是否插入成功
        if(row != 1) {
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常 - ApplicationException FAILED_CREATE           (1004, "新增失败"),
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //打印日志
        log.info("新增用户成功, userName = " + user.getUsername() );
    }


    /**
     * 根据用户名查询用户信息
     * @param username 用户名
     * @return
     */
    @Override
    public User selectByUserName(String username) {
        if(StringUtil.isEmpty(username)) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }

    /**
     * 登录方法
     * @param username 用户名
     * @param password 加密密码(密文)
     * @return
     */
    @Override
    public User login(String username, String password) {
        //参数校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            //打印错误日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //抛异常    FAILED_LOGIN            (1103,"用户名或密码错误"),
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //查询用户信息
        User user = selectByUserName(username);
        //对查询的用户信息做非空校验
        if(user == null) {
            //打印错误日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + "," + "username = " + username);
            //抛异常    FAILED_LOGIN            (1103,"用户名或密码错误"),
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //对密码进行校验
        String salt = user.getSalt();
        String preparePwd = MD5Util.md5Salt(password,salt);
        if(!user.getPassword().equalsIgnoreCase(preparePwd)) {
            //打印错误日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + "," + "密码不匹配->username = " + username);
            //抛异常    FAILED_LOGIN            (1103,"用户名或密码错误"),
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        log.info(username + "--登录成功--");
        return user;
    }

    @Override
    public User selectById(Long id) {
        //非空校验
        if(id == null) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用Dao查询数据库
        User user = userMapper.selectByPrimaryKey(id);
        //返回结果
        return user;
    }


    /**
     * 更新当前用户的发帖数
     * @param id
     */
    @Override
    public void addOneArticleCountById(Long id) {
        if(id == null || id <= 0) {
            //FAILED_USER_ARTICLE_COUNT (1201, "更新用户帖子数量失败"),
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        //查询发布帖子的用户
        User user = userMapper.selectByPrimaryKey(id);
        //没有找到相关的用户
        if(user == null) {
            //  ERROR_IS_NULL           (2001, "IS NULL.");
            log.warn(ResultCode.ERROR_IS_NULL.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新文章数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        //调用动态更新的SQL语句 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //判断受影响的行数
        if(row != 1) {
            //  FAILED                  (1000, "操作失败"),
            log.warn(ResultCode.FAILED .toString() + "更新数据库异常");

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED ));
        }
    }

    /**
     * 用户发帖数量 -1
     * @param id
     */
    @Override
    public void subOneArticleCountById(Long id) {
        if(id == null || id <= 0) {
            //FAILED_USER_ARTICLE_COUNT (1201, "更新用户帖子数量失败"),
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        //查询发布帖子的用户
        User user = userMapper.selectByPrimaryKey(id);
        //没有找到相关的用户
        if(user == null) {
            //  ERROR_IS_NULL           (2001, "IS NULL.");
            log.warn(ResultCode.ERROR_IS_NULL.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新文章数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        if(user.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }
        //调用动态更新的SQL语句 更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //判断受影响的行数
        if(row != 1) {
            //  FAILED                  (1000, "操作失败"),
            log.warn(ResultCode.FAILED.toString() + "更新数据库异常");

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }


    /**
     * 修改用户信息
     * @param user
     */
    @Override
    public void modifyInfo(User user) {
        //校验参数
        if(user == null || user.getId() == null || user.getId() <= 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser == null) {
            //FAILED_USER_NOT_EXISTS  (1102,"用户不存在"),
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //定义一个标志位
        boolean checkAttr = false;

        //  定义一个专门用来更新的对象，防止用户传入的User对象设置了其他的属性
        // 当使用动态SQL进行更新的时候，覆盖了没有经过校验的字段
        User updateUser = new User();
        //  设置用户Id
        updateUser.setId(user.getId());
//        //1.校验用户名
//        if(!StringUtil.isEmpty(user.getUsername())
//                && !user.getUsername().equals(existsUser.getUsername()) ) {
//            //用户名唯一性校验
//            User checkUser = userMapper.selectByUserName(user.getUsername());
//            if(checkUser != null) {
//                //    FAILED_USERNAME_EXISTS      (1107,"用户名已存在"),
//                log.info(ResultCode.FAILED_USERNAME_EXISTS.toString());
//
//                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USERNAME_EXISTS));
//            }
//            updateUser.setUsername(user.getUsername());
//            checkAttr = true;
//        }

        //2.校验昵称
        if(!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }

//        //校验性别
//        if(user.getGender() != null
//                && user.getGender() != existsUser.getGender()) {
//            updateUser.setGender(user.getGender());
//            // 合法性校验
//            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
//                updateUser.setGender((byte) 2);
//            }
//            checkAttr = true;
//        }

        //校验邮箱
        if(!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }

        //校验电话号码
        if(!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }

        //  校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            // 设置电话号码
            updateUser.setRemark(user.getRemark());
            // 更新标志位
            checkAttr = true;
        }

        //标志位检查是否执行修改用户信息
        if(!checkAttr) {
            //    FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //调用dao层
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1) {
            //  FAILED                  (1000, "操作失败"),
            log.warn(ResultCode.FAILED.toString() + "更新数据库异常");

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    /**
     * 修改密码
     * @param id 用户id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     */
    @Override
    public void modifyPassWord(Long id, String newPassword, String oldPassword) {
       //非空校验
        if(id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            //FAILED_USER_ARTICLE_COUNT (1201, "更新用户帖子数量失败"),
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState() == 1) {
            //FAILED_USER_NOT_EXISTS  (1102,"用户不存在"),
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验老密码是否正确
        String oldEncryptPwt = MD5Util.md5Salt(oldPassword, user.getSalt());
        //与用户当前的密码进行比较
        if(!oldEncryptPwt.equalsIgnoreCase(user.getPassword())) {
            //FAILED                  (1000, "操作失败"),
            log.info(ResultCode.FAILED.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

        //修改密码
        //生成一个新盐
        String salt = UUIDUtil.UUID_32();
        String password = MD5Util.md5Salt(newPassword,salt);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(password);
        Date date = new Date();
        updateUser.setUpdateTime(date);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1) {
            //  FAILED                  (1000, "操作失败"),
            log.warn(ResultCode.FAILED.toString() + "更新数据库异常");

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

}
